package com.test.redis_demo.controller;

import com.test.redis_demo.model.CommonValue;
import com.test.redis_demo.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("index")
public class IndexController {
    @Autowired
    RedisService redisService;
    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    @RequestMapping(value = "first", produces = "text/html")
    @ResponseBody
    public String index(HttpServletRequest request, HttpServletResponse response, Model model){
        String html = (String) redisService.getVal(CommonValue.INDEX_HTML);
        if (!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("data","这是一句测试的话。");
        // 渲染页面
        IWebContext swc =new WebContext(request,response,
                request.getServletContext(),request.getLocale(),model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("demoPage",swc);
        if (!StringUtils.isEmpty(html)){
            redisService.setVal(CommonValue.INDEX_HTML,html);
        }
        return html;
    }
}
